package com.yf.ability.config.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.ability.config.dto.CfgPropDTO;
import com.yf.ability.config.entity.CfgProp;
import com.yf.ability.config.mapper.CfgPropMapper;
import com.yf.ability.config.service.CfgPropService;
import com.yf.base.api.exception.ServiceException;
import com.yf.base.utils.BeanMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* <p>
* 上传配置业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2022-03-22 17:46
*/
@Service
public class CfgPropServiceImpl extends ServiceImpl<CfgPropMapper, CfgProp> implements CfgPropService {

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "sys:config", allEntries=true)
    @Override
    public void save(CfgPropDTO reqDTO) {

        String json = JSON.toJSONString(reqDTO);

        // 有脱敏数据
        if(json.contains("**")){
            throw new ServiceException("请填写正确配置，敏感数据`***`后必须重新填写才能保存！");
        }

        // 保存
        this.clearEnabled(reqDTO.getType());

        // 直接删除
        QueryWrapper<CfgProp> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(CfgProp::getType, reqDTO.getType())
                .eq(CfgProp::getProvider, reqDTO.getProvider());
        this.remove(wrapper);

        // 复制参数
        CfgProp entity = new CfgProp();
        BeanMapper.copy(reqDTO, entity);
        entity.setId(IdWorker.getIdStr());
        entity.setEnabled(true);
        this.save(entity);

    }

    //@Cacheable(value = "sys:config", key = "#type+'-'+#provider")
    @Override
    public CfgPropDTO detail(String type, String provider) {

        //分页查询并转换
        QueryWrapper<CfgProp> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CfgProp::getType, type);

        CfgProp entity = null;

        // 查找默认的
        if (StringUtils.isBlank(provider) || "default".equals(provider)) {
            wrapper.lambda().eq(CfgProp::getEnabled, true);
            entity = this.getOne(wrapper, false);
        } else {
            wrapper.lambda().eq(CfgProp::getProvider, provider);
            entity = this.getOne(wrapper, false);
        }

        CfgPropDTO dto = new CfgPropDTO();
        BeanMapper.copy(entity, dto);
        System.out.println("查询配置：" + dto);
        return dto;
    }

    /**
     * 清除使用状态
     */
    private void clearEnabled(String type) {
        QueryWrapper<CfgProp> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(CfgProp::getType, type);
        CfgProp entity = new CfgProp();
        entity.setEnabled(false);
        this.update(entity, wrapper);
    }
}
